<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class UserCard extends Backend
{

    /**
     * UserCard模型对象
     * @var \app\admin\model\UserCard
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\UserCard;
        $this->view->assign("statusList", $this->model->getStatusList());
    }


    public function index()
    {

        //带入记录id
        $ids = $this->request->request("ids");
        $where5 = [];
        if($ids){
            $where5 = " id in ($ids)";
            $this->assign("ids",$ids);
        }else{
            $this->assign("ids","");
        }

        //带入用户id 用户入口
        $uid = $this->request->request("uid");
        $where4 = [];
        if($uid){
            $where4 = " `uid` = $uid";
            $this->assign("uid",$uid);
        }else{
            $this->assign("uid","");
        }

        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams("nickname");
            $total = $this->model
                ->where($where)
                ->where($where4)
                ->where($where5)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->where($where4)
                ->where($where5)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();

            foreach ($list as $k => $v){
                $cid = $v['c_id'];
                $card = db('card')->where("id = $cid")->find();
                $list[$k]['c_id']=$card['cardname'];
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }


    public function add()
    {

        $card=db('card')->where("status = '0' ")->select();


        $this->assign('card',$card);

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            if ($params) {
                $num = $params['nnum'];
                unset($params['nnum']);
                if($num>=50){
                    $this->error('数量请小于50');die;
                }
                $cid = $params['c_id'];
                $card2=db('card')->where("id =  $cid")->find();

                $params['less_hours']=$card2['hours'];
                for ($x=1; $x<=$num; $x++) {
                     $code = $this->generate_password();
                     $params['d_number']=$code;

                     $save = db('user_card')->insert($params);
                     if(!$save){
                         $this->error('添加失败');
                     }
                }


                $this->success('添加成功');
//                $params = $this->preExcludeFields($params);
//                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
//                    $params[$this->dataLimitField] = $this->auth->id;
//                }
//                $result = false;
//                Db::startTrans();
//
//
//
//                try {
//                    //是否采用模型验证
//                    if ($this->modelValidate) {
//                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
//
//
//                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
//                        $this->model->validateFailException(true)->validate($validate);
//                    }
//
//
//                    $result = $this->model->allowField(true)->save($params);
//
//
//                    Db::commit();
//                } catch (ValidateException $e) {
//                    Db::rollback();
//                    $this->error($e->getMessage());
//                } catch (PDOException $e) {
//                    Db::rollback();
//                    $this->error($e->getMessage());
//                } catch (Exception $e) {
//                    Db::rollback();
//                    $this->error($e->getMessage());
//                }
//                if ($result !== false) {
//                    $this->success();
//                } else {
//                    $this->error(__('No rows were inserted'));
//                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }


    public function del($ids = "")
    {


        if ($ids) {

            $m=db('user_card')->where("id = $ids")->find();
            if($m['status'] == 0){

            }else{
                $this->error('此卡已被兑换,请勿删除');
            }
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }


    function generate_password( $length = 11 ) {
// 密码字符集，可任意添加你需要的字符
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $password = '';
            for ( $i = 0; $i < $length; $i++ )
            {
            // 这里提供两种字符获取方式
            // 第一种是使用 substr 截取$chars中的任意一位字符；
            // 第二种是取字符数组 $chars 的任意元素
            // $password .= substr($chars, mt_rand(0, strlen($chars) – 1), 1);
                $password .= $chars[ mt_rand(0, strlen($chars) - 1) ];
            }
            return $password;
            }


    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


}
